<?php

namespace Admin\Controller;
use Think\Controller;
class CommonController extends Controller{
    public function _initialize() {
        if( !$_SESSION['uid'] && !$_SESSION['username'] ) {
            redirect( U('Public/login') ); 
        }

        $Auth = new \Think\Auth();
        if(C('ADMINISTRATOR_USER') !== $_SESSION['uid']) {
            if( !$Auth->check( MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME, $_SESSION['uid']) ) {
                $this->error('您没有权限！');
            }
        }
        $this->assign('__MENU__', $this->getMenus());
    }

    final public function getMenus($controller=CONTROLLER_NAME){
        if(empty($menus)){
            // 获取主菜单
            $where['pid']   =   0;
            $where['hide']  =   0;

            $menus['main']  =   M('Menu')->where($where)->order('sort asc')->select();

            $menus['child'] = array(); //设置子节点

            //高亮主菜单
            $current = M('Menu')->where("url like '%{$controller}/".ACTION_NAME."%'")->field('id')->find();
            if($current){
                $nav = D('Menu')->getPath($current['id']);
                $nav_first_title = $nav[0]['title'];

                foreach ($menus['main'] as $key => $item) {
                    if (!is_array($item) || empty($item['title']) || empty($item['url']) ) {
                        $this->error('控制器基类$menus属性元素配置有误');
                    }
                    if( stripos($item['url'],MODULE_NAME)!==0 ){
                        $item['url'] = MODULE_NAME.'/'.$item['url'];
                    }

                    // 获取当前主菜单的子菜单项
                    if($item['title'] == $nav_first_title){
                        $menus['main'][$key]['class'] = 'active';
                        //生成child树
                        $groups = M('Menu')->where("pid = {$item['id']}")->distinct(true)->field("`group`")->select();
                        if($groups){
                            $groups = array_column($groups, 'group');
                        }else{
                            $groups =   array();
                        }
                        header("Content-type:text/html;charset=utf-8");

                        //获取二级分类的合法url
                        $where          =   array();
                        $where['pid']   =   $item['id'];
                        $where['hide']  =   0;

                        $second_urls = M('Menu')->where($where)->getField('id,url');
                        
                        // 按照分组生成子菜单树
                        foreach ($groups as $g) {
                            $map = array('group'=>$g);
                            if(isset($to_check_urls)){
                                if(empty($to_check_urls)){
                                    // 没有任何权限
                                    continue;
                                }else{
                                    $map['url'] = array('in', $to_check_urls);
                                }
                            }
                            $map['pid']    =   $item['id'];
                            $map['hide']   =   0;

                            $menuList = M('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort asc')->select();
                            $menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
                        }
                    }
                }
            }
            // session('ADMIN_MENU_LIST'.$controller,$menus);
        }
        return $menus;
    }
    
    /**
     * 通用分页列表数据集获取方法
     * @param  [type]  $model 模型名或模型实例
     * @param  array   $map   查询条件
     * @param  string  $sort  排序
     * @param  boolean $field 指定查询字段
     * @return [type]         返回结果集
     */
    public function _list( $model, $map = array(), $sort = 'id desc', $field = true) {
        $total = $model->where( $map )->count();
        $rows = C('LIST_ROWS') ? C('LIST_ROWS') : 10;
        $page = new \Think\Page( $total, $rows );
        $list = $model->where( $map )->order( $sort )->field( $field )->limit( $page->firstRow . ',' . $page->listRows )->select();
        if($total>$rows){
            $page->setConfig('theme',  '<ul class="pagination"> <li>%FIRST%</li> <li> %UP_PAGE% </li> <li>%LINK_PAGE%</li> <li> %DOWN_PAGE% </li> <li>%END%</li> </ul>');
        }
        $p = $page->show();
        $this->assign('list', $list);
        $this->assign('_page', $p ? $p : '');
        return;
    }

    /**
     * 删除操作
     */
    public function del( $model = CONTROLLER_NAME ) {
        if( !$model->where(array('id'=>I('get.id')))->delete() ) {
            $this->error('删除失败！');
        }else{
            $this->success('删除成功！');
        }
    }

    /**
     * 图片上传
     * @param  boolean $thumb       是否生成缩略图
     * @param  string  $thumbWidth  缩略图宽度
     * @param  string  $thumbHeight 缩略图高度
     * @return [type]               上传成功或失败结果集
     */
    Public function _upload( $thumb = false , $thumbWidth = '' , $thumbHeight = '') {
        $upload = new \Think\Upload();
        $upload->maxSize = C('UPLOAD_FILE_SIZE') ;
        $upload->exts =  array('jpg', 'gif', 'png', 'jpeg');
        $upload->savePath =  '/' . CONTROLLER_NAME .'/'; // 设置附件上传目录
        $info = $upload->upload();
        if(!$info) {
            return array('status' =>0, 'info'=> $upload->getError() );
        }else{
            if( $thumb ) {    //生成缩略图

                $image = new \Think\Image(); 

                foreach($info as $file) {
                    $thumb_file = './Uploads/' . $file['savepath'] . $file['savename'];
                    $save_path = './Uploads/' .$file['savepath'] . 'mini_' . $file['savename'];
                    //$image->open( $thumb_file )->text('德兴房产','./data/1.otf',30,'#A7AAA4',\Think\Image::IMAGE_WATER_CENTER)->save( $thumb_file );
                    //$image->open( $thumb_file )->text('德兴房产','./data/1.otf',24,'#A7AAA4',\Think\Image::IMAGE_WATER_CENTER)->thumb( $thumbWidth, $thumbHeight )->save( $save_path );
                    return array(
                        'status' => 1, 
                        'savepath' => $file['savepath'],
                        'savename' => $file['savename'],
                        'pic_path' => $file['savepath'] . $file['savename'],
                        'mini_pic' => $file['savepath'] . 'mini_' .$file['savename']
                    );   
                }
            }else{
                foreach($info as $file) {
                    return array(
                        'status' => 1, 
                        'savepath' => $file['savepath'],
                        'savename' => $file['savename'],
                        'pic_path' => $file['savepath'].$file['savename']
                    );   
                }
            }
        }
    }

    //编辑器图片上传
    Public function editor_upload_pic(){
        $info = $this->_upload('ueditor');
        $editorId=$_GET['editorid'];
        echo "<script>parent.UM.getEditor('". $editorId ."').getWidgetCallback('image')('" . $info['pic_path'] . "','SUCCESS')</script>";
    }

}